﻿#include "saveproject.h"
#include "ui_saveproject.h"
#include "commdefine.h"
#include <QFileDialog>
#include <QListWidget>
#include <QMessageBox>

SaveProject::SaveProject(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SaveProject)
{
    ui->setupUi(this);

    setLayout(ui->verticalLayout);
}

SaveProject::~SaveProject()
{
    delete ui;
}

void SaveProject::setConfigInfo(const QJsonArray &config)
{
    if(m_config != config) {
        m_config = config;
    }

    ui->listWidget->clear();
    for(auto d : m_config) {
        QJsonObject obj = d.toObject();

        if("project" == obj["type"].toString()) {
            QListWidgetItem *item = new QListWidgetItem(obj["name"].toString());
            ui->listWidget->addItem(item);
        }
    }

    show();
}

void SaveProject::on_pushButton_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("新建工程"));
    if(!fileName.contains(".proj"))
        fileName += ".proj";

    QString name = getFileNameByPath(fileName);
    name.replace(".proj", "");
    QListWidgetItem *item = new QListWidgetItem(name);
    ui->listWidget->addItem(item);

    emit newProject(fileName);
}

void SaveProject::on_buttonBox_accepted()
{
    // 判断是否选中工程
    QListWidgetItem *item = ui->listWidget->currentItem();
    if(item == nullptr) {
        QMessageBox::warning(this, tr("警告"), tr("请先选择工程"));
        return;
    }
    else {
        QString name = item->text();
        for(auto d : m_config) {
            QJsonObject obj = d.toObject();
            if("project" == obj["type"].toString() && name == obj["name"].toString()) {
                emit chooseProject(obj["path"].toString());
                break;
            }
        }
    }
}
